// 创建mask dom
const mask = document.querySelector(".mask");
console.log(mask);

class Game {
  constructor() {
    this.sky = new Sky();
    this.land = new Land(-100);
    this.bird = new Bird();
    // 生成柱子对
    this.pipeProducer = new PipePareProducer(-100);
    this.timer = null;
    this.tick = 16;
    this.gameOver = false;
  }

  // 开始游戏
  startGame() {
    if (this.timer) return;

    if (this.isGameOver()) window.location.reload();

    this.pipeProducer.startProduce();

    // 开启定时器
    this.timer = setInterval(() => {
      const duration = this.tick / 1000;
      this.sky.move(duration);
      this.land.move(duration);
      this.bird.move(duration);
      this.pipeProducer.pairs.forEach((pair) => {
        pair.move(duration);
      });

      if (this.isGameOver()) {
        this.pauseGame();
        this.gameOver = true;
        console.log("游戏结束了");
      }
    }, this.tick);
  }

  //   是否游戏结束
  isGameOver() {
    // 碰到了大地
    if (this.bird.top === this.bird.maxY) {
      return true;
    }

    // 触碰到了柱子
    for (let i = 0; i < this.pipeProducer.pairs.length; i++) {
      const pair = this.pipeProducer.pairs[i];

      const upPipe = pair.upPipe;
      const downPipe = pair.downPipe;
      if (this.isHit(this.bird, upPipe) || this.isHit(this.bird, downPipe))
        return true;
    }

    return false;
  }

  isHit(rec1, rec2) {
    const centerX1 = rec1.left + rec1.width / 2;
    const centerY1 = rec1.top + rec1.height / 2;

    const centerX2 = rec2.left + rec2.width / 2;
    const centerY2 = rec2.top + rec2.height / 2;

    const disX = Math.abs(centerX1 - centerX2);
    const disY = Math.abs(centerY1 - centerY2);

    if (
      disX < (rec1.width + rec2.width) / 2 &&
      disY < rec1.height + rec2.height
    ) {
      return true;
    }

    return false;
  }

  // 暂停游戏
  pauseGame() {
    clearInterval(this.timer);
    this.timer = null;
    this.bird.stopFly();
    this.pipeProducer.stopProduce();
  }

  // 键盘事件
  regEvent() {
    window.onkeydown = (event) => {
      if (event.key === "Enter") {
        if (this.timer) {
          // 设置遮罩层
          mask.className = 'mask unshow'
          this.pauseGame();
        } else {
          // 设置遮罩层
          mask.style.display = "mask show";
          this.startGame();
        }
      } else if (event.key === " ") {
        this.bird.jump();
      }
    };
  }
}
